package com.xxxx.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxxx.server.Utils.DateUtils;
import com.xxxx.server.mapper.InucleicMapper;
import com.xxxx.server.mapper.SnucleicMapper;
import com.xxxx.server.pojo.*;
import com.xxxx.server.service.IInucleicService;
import com.xxxx.server.service.ISnucleicService;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 学生核酸登记登记表 前端控制器
 * </p>
 *
 * @author zhoubin
 * @since 2022-06-04
 */
@RestController
@RequestMapping("/nuc/stu/")
public class SnucleicController {

    @Autowired
    private ISnucleicService iSnucleicService;
    @Autowired
    private SnucleicMapper snucleicMapper;

    @ApiOperation(value = "添加学生核酸信息（用户添加）")
    @PostMapping("/post")
    public RespBean addSnucleic(@RequestBody Snucleic snucleic){

        QueryWrapper<Snucleic> wrapper = new QueryWrapper<>();
        wrapper.eq("SNid",((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
        wrapper.eq("enable",1);
        List<Snucleic> arry = snucleicMapper.selectList(wrapper);
        for (int i = 0; i < arry.size(); i++) {
            arry.get(i).setEnable(0);
        }
        iSnucleicService.updateBatchById(arry);

        snucleic.setSNid(((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
        snucleic.setSNdate(LocalDateTime.now());
        snucleic.setEnable(1);
        if (iSnucleicService.save(snucleic)){
            return RespBean.success("添加成功！");
        }
        return RespBean.error("添加失败!");
    }

    @ApiOperation(value = "更新学生核酸信息（用户更新）")
    @PutMapping("/update")
    public RespBean updateSnucleic(@RequestBody Snucleic snucleic){
        snucleic.setSNid(((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
        snucleic.setEnable(1);
        if (iSnucleicService.updateById(snucleic)){
            return RespBean.success("更新成功！");
        }
        return RespBean.error("更新失败！");
    }

    @ApiOperation(value = "查询所有的学生核酸（分页）")
    @GetMapping("/getPageSnucleic/")
    public RespPageBean getSnucleicByPage(@RequestParam(defaultValue = "1") Integer currentPage ,
                                     @RequestParam(defaultValue = "10")Integer size,
                                     Snucleic snucleic,
                                     String[] beginDateScope,
                                     String collegename,
                                     String classname){
        Admin admin = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int type=admin.getRoles().get(0).getId();
        int collegeid;
        if(admin.getCollegeid()!=null){
            collegeid = admin.getCollegeid();
        }else{
            collegeid=0;
        }
        int classid;
        if(admin.getClassid()!=null){
            classid = admin.getClassid();
        }else{
            classid=0;
        }
        return iSnucleicService.getSnucleicByPage(currentPage,size,snucleic,beginDateScope,type,collegename,collegeid,classid,classname);
    }

    @ApiOperation(value = "登录的学生核酸上报是否有效（用户查询）")
    @PutMapping("/isEffective")
    public int isEffectiveInucleic() throws ParseException {
        QueryWrapper<Snucleic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("enable",1);
        queryWrapper.eq("SNid",((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
        Snucleic snucleic = iSnucleicService.getOne(queryWrapper);
        if(snucleic == null)
            return 0;

        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
        String recordtime = snucleic.getTest3time().toString();
        recordtime = recordtime.substring(0,10);
        Date rt = ft.parse(recordtime);
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(rt);
        rightNow.add(Calendar.DAY_OF_MONTH, 7);
        Date endtime = rightNow.getTime();


        String nowtime = LocalDateTime.now().toString();
        nowtime = nowtime.substring(0,10);
        Date nowTime = ft.parse(nowtime);;

        boolean effectiveDate = DateUtils.isEffectiveDate(nowTime, rt, endtime);
        if (effectiveDate) {
            return 1;
        }else {
            return 0;
        }
    }

    @ApiOperation(value = "导出学生核酸检测数据")
    @GetMapping(value = "/export",produces = "application/octet-stream")
    public void exportSnucleic(HttpServletResponse response,
                               Snucleic snucleic,
                               String[] beginDateScope,
                               String collegename,
                               String classname){
        Admin admin = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int type=admin.getRoles().get(0).getId();
        int collegeid;
        if(admin.getCollegeid()!=null){
            collegeid = admin.getCollegeid();
        }else{
            collegeid=0;
        }
        int classid;
        if(admin.getClassid()!=null){
            classid = admin.getClassid();
        }else{
            classid=0;
        }
        List<Snucleic> list = iSnucleicService.getSnucleicSeachList(snucleic,beginDateScope,type,collegename,collegeid,classid,classname);
        ExportParams params = new ExportParams("学生核酸检测情况表","学生核酸检测情况表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Snucleic.class, list);
        ServletOutputStream out = null;
        try {
            //流形式
            response.setHeader("content-type","application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("学生核酸检测情况表.xls","UTF-8"));
            out = response.getOutputStream();
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (null!=out){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
